<?php

namespace App\Console\Commands;

use App\Models\Archive;
use App\Models\Category;
use App\Models\File;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class SyncOldPicture extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'zx:sync-old-picture {--test}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '同步旧版图片';

    public $createArchiveCount = 0;
    public $createPictureCount = 0;
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $page = Cache::rememberForever('sync_old_pictures_page', function() {
            return 1;
        });
        $last_page = $page;
        $total = 0;
        $url = 'http://180.76.180.42:8088/api/v1/all/pictures';
        if ($this->option('test')) {
            $response = Http::get($url,[
                'page' => $page
            ]);
            dd($response->json());
        }
        while($page <= $last_page) {
            $this->info(sprintf('正在处理第 %d 页数据', $page));
            $response = Http::get($url,[
                'page' => $page
            ]);

            $data = $response->json();
            foreach($data['data'] as $d) {
                $total++;
                $archive = $this->createNewArchiveByTitle($d['title'], $d['tags']);
                $this->saveFile($archive, $d);
            }
            $this->info(sprintf('完成第 %d 页数据处理', $page));
            Cache::put('sync_old_pictures_page', $page);
            $page++;
            $last_page = $data['meta']['last_page'];
        }
        $this->info(sprintf('完成所有数据处理, 共处理数据 %d 条图片数据, 新建了 %d 个文档, 存储了 %d 个图片', $total, $this->createArchiveCount, $this->createPictureCount));
    }

    public function saveFile($archive, $picture)
    {
        $file = new File(Arr::only($picture, ['file', 'md5', 'color', 'size', 'width', 'height', 'type']));
        $file->is_cdn = true;
        $file->color = str_replace('#', '', $file->color);
        if ($file->color === '000') $file->color = null;
        if (! File::where(['archive_id' => $archive->id, 'md5' => $file->md5])->first()) {
            $archive->files()->save($file);
            $this->createPictureCount++;
        }
    }

    public function createNewArchiveByTitle($title, $tags = [])
    {
        $removeTags = ['[]', '头像', '唯美图', '美图', '唯美', '壁纸'];
        $replaceTags = ['影视,体育' => '影视'];
        $categoryIdMap = [
            '头像' => 1,
            '壁纸' => 3,
            '唯美' => 2,
            '唯美图' => 2
        ];
        $newTags = [];
        foreach($tags as $tag)
        {
            if (isset($replaceTags[$tag])) {
                $tag = $replaceTags[$tag];
            }
            if (isset($categoryIdMap[$tag])) {
                $category_id = $categoryIdMap[$tag];
            } else {
                $category_id = 2;
            }
            if (!in_array($tag, $removeTags)) {
                $newTags[] = $tag;
            }
        }
        $archive = Archive::firstOrCreate([
            'title' => $title,
            'category_id' => $category_id
        ], [
            'user_id' => 1,
        ]);
        if ($archive->wasRecentlyCreated) {
            $this->createArchiveCount++;
        }
        $archive->retag($newTags);
        return $archive;
    }
}
